<template>
  <view class="account-form">
    <sar-form ref="loginFormRef" :model="form" :rules="rules">
      <!-- 用户名输入框 -->
      <sar-form-item name="username">
        <sar-input
          v-model="form.username"
          type="text"
          placeholder="请输入账号"
          root-class="login-input"
        >
          <template #prepend>
            <sar-icon class="ml-2" :name="IconUser" size="36rpx" color="#3977FE" />
          </template>
        </sar-input>
      </sar-form-item>

      <!-- 密码输入框 -->
      <sar-form-item name="password">
        <sar-input
          v-model="form.password"
          :type="passwordVisible ? 'text' : 'password'"
          placeholder="请输入密码"
          root-class="login-input"
        >
          <template #prepend>
            <sar-icon class="ml-2" :name="IconPassword" size="36rpx" color="#3977FE" />
          </template>
          <template #append>
            <view @click="togglePasswordVisible">
              <sar-icon
                :name="passwordVisible ? IconEyeOpen : IconEyeClose"
                size="36rpx"
                color="#999"
              ></sar-icon>
            </view>
          </template>
        </sar-input>
      </sar-form-item>

      <!-- 验证码输入框 -->
      <sar-form-item v-if="captchaInfo.isEnabled" name="captcha">
        <sar-input
          v-model="form.captcha"
          type="text"
          placeholder="请输入验证码"
          root-class="login-input"
        >
          <template #prepend>
            <sar-icon class="ml-2" :name="IconCode" size="36rpx" color="#3977FE" />
          </template>
          <template #append>
            <view class="captcha-container" @click="refreshCaptcha">
              <image v-if="!isCaptchaExpired" :src="captchaInfo.img" class="captcha-image" />
              <view v-else class="captcha-expired">已过期，请刷新</view>
            </view>
          </template>
        </sar-input>
      </sar-form-item>

      <!-- 底部操作区域 -->
      <view class="flex items-center justify-end mt-[15rpx] mb-[25rpx]">
        <text class="text-[24rpx] text-[#3977FE]" @click="emit('forgotPassword')">忘记密码?</text>
      </view>

      <!-- 登录按钮 -->
      <sar-button
        form-type="submit"
        root-class="login-btn !w-full !rounded-[44rpx]"
        :plain="false"
        :loading="loading"
        block
        @click="handleSubmit"
      >
        登录
      </sar-button>
    </sar-form>

    <!-- 注册提示 -->
    <view class="register-tip mt-[15rpx] flex justify-center">
      <text class="text-[24rpx] text-[#666]">还没有账号？</text>
      <text class="text-[24rpx] text-[#3977FE] ml-[10rpx]" @click="emit('register')">立即注册</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import type { ImageCaptchaResp } from '@/apis/common/captcha'
import { getImageCaptcha } from '@/apis/common/captcha'

import IconEyeClose from '@/static/images/login/eye-close.svg'
import IconEyeOpen from '@/static/images/login/eye-open.svg'
import IconCode from '@/static/images/login/icon_code.svg'
import IconUser from '@/static/images/login/login_user.svg'
import IconPassword from '@/static/images/login/password.svg'
import { useAuthStore } from '@/store/auth'
import { encryptByRsa } from '@/utils/encrypt'
import { deepClone, type FormExpose, type FormRules, toast } from 'sard-uniapp'

defineProps({
  loading: Boolean,
})
const emit = defineEmits([
  'submit',
  'forgotPassword',
  'register',
])
const authStore = useAuthStore()
const captchaInfo = ref<Partial<ImageCaptchaResp>>({
  isEnabled: false,
})
const loginFormRef = ref<FormExpose>()
const passwordVisible = ref(false)
const form = ref({
  username: 'admin',
  password: 'admin123',
  captcha: '',
  uuid: '',
})

// 验证码过期状态
const isCaptchaExpired = ref<boolean>(false)

// 验证码过期定时器
let captchaTimer: ReturnType<typeof setTimeout> | null = null

// 设置验证码过期定时器
function startCaptchaTimer(expireTime: number, curTime = Date.now()) {
  // 清除之前的定时器
  if (captchaTimer) {
    clearTimeout(captchaTimer)
    captchaTimer = null
  }

  // 计算剩余时间
  const remainingTime = expireTime - curTime

  // 如果已经过期，直接标记
  if (remainingTime <= 0) {
    isCaptchaExpired.value = true
    return
  }

  // 未过期则重置状态
  isCaptchaExpired.value = false

  // 设置定时器，在验证码过期时触发
  captchaTimer = setTimeout(() => {
    isCaptchaExpired.value = true
  }, remainingTime)
}

onShow(async () => {
  await refreshCaptcha()
})

onMounted(() => {
  // 组件挂载后，如果有过期时间，设置定时器
  if (captchaInfo.value.expireTime) {
    startCaptchaTimer(captchaInfo.value.expireTime)
  }
})

onBeforeUnmount(() => {
  // 组件销毁前清理定时器
  if (captchaTimer) {
    clearTimeout(captchaTimer)
    captchaTimer = null
  }
})

// 表单验证规则
const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入账号' },
  ],
  password: [
    { required: true, message: '请输入密码' },
  ],
  captcha: [
    { required: captchaInfo.value.isEnabled, message: '请输入验证码' },
  ],
})

// 切换密码显示状态
function togglePasswordVisible() {
  passwordVisible.value = !passwordVisible.value
}

// 刷新验证码
async function refreshCaptcha() {
  try {
    const response = await getImageCaptcha()
    const { data } = response
    const { uuid, expireTime } = data

    // 更新验证码信息
    captchaInfo.value = data

    // 重置过期状态
    isCaptchaExpired.value = false

    // 更新表单
    form.value.uuid = uuid

    // 设置过期定时器，优先使用响应的时间戳
    if (expireTime) {
      // 使用响应中的时间戳（如果有的话）或当前时间
      const timestamp = response.timestamp ? Number(response.timestamp) : Date.now()
      startCaptchaTimer(expireTime, timestamp)
    }

    // 如果验证码输入过，则清空
    if (form.value.captcha) {
      form.value.captcha = ''
    }
  }
  catch {
    toast('获取验证码失败', { position: 'center' })
  }
}

// 提交表单，处理账号登录逻辑
async function handleSubmit() {
  try {
    if (!loginFormRef.value) {
      toast('表单引用获取失败', { position: 'center' })
      return
    }

    // 检查验证码是否已过期
    if (captchaInfo.value.isEnabled && isCaptchaExpired.value) {
      toast('验证码已过期，请刷新', { position: 'center' })
      return
    }

    // 表单验证
    await loginFormRef.value.validate()
    const loginParam = deepClone(form.value)
    // 密码加密
    loginParam.password = encryptByRsa(loginParam.password)
    loginParam.uuid = captchaInfo.value.uuid
    const success = await authStore.authLogin(loginParam, 'ACCOUNT')
    // 抛出提交事件
    emit('submit', {
      success,
    })
    getImageCaptcha()
  }
  catch {
    // 登录表单校验不通过
  }
}

// 重置表单
function resetForm() {
  if (loginFormRef.value) {
    loginFormRef.value.reset()
  }
}

// 导出组件方法供父组件调用
defineExpose({
  resetForm,
})
</script>

<style lang="scss" scoped>
.account-form {
  padding: 0 5rpx;
}

.captcha-container {
  position: relative;
  width: 110rpx;
  height: 56rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.captcha-image {
  width: 110rpx;
  height: 56rpx;
  object-fit: contain;
  display: block;
}

.captcha-expired {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20rpx;
  text-align: center;
  background: linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5));
  border-radius: 4rpx;
  cursor: pointer;
  line-height: 1.2;
}

.login-input {
  --sar-input-padding-x: 0;
  --sar-input-height: 76rpx;
  --sar-input-line-height: 1.2;
  margin-bottom: 15rpx;
}

.login-btn {
  --sar-button-height: 80rpx;
  --sar-button-primary-color: #FFFFFF !important;
  --sar-button-primary-background-color: #3977FE !important;
  --sar-button-primary-border-color: #3977FE !important;
  --sar-button-primary-active-background-color: #3369E8 !important;
  --sar-button-primary-active-border-color: #3369E8 !important;
}

.register-tip {
  margin-top: 15rpx;
}

.flex.items-center.justify-end {
  margin-top: 15rpx;
  margin-bottom: 25rpx;
}
</style>
